#include <stdlib.h>
// #include <stdio.h>
#include <string.h>

#include <debug.h>
#include <os_api.h>
#include <atclient.h>

#define TASK_STACK_SIZE (10 * 1024)

const char *atcmdlist[] = {
	"AT+CPIN?\r",
	"AT+CIMI\r",
	"AT+CSQ\r",
	"AT+CGDCONT?\r",
};

void atclient_get_indication(const char *string)
{
	LOG_PRINTF("ind: %s", string);
	if (strstr(string, "^MODE:"))
	{
		char *p, *e;
		int mode;

		p = strchr(string, ':');
		if (!p)
			return;
		p++;
		while (*p != '\0' && *p <= 0x20) // skip space
			p++;
		e = p;
		while (*e != '\0' && *e > 0x20 && *e < 0x7f) // to end
			e++;
		*e = '\0';
		mode = atoi(p);
		LOG_PRINTF("Mode is %d", mode);
	}
}

static void atclient_task(void *param)
{
	unsigned count = 0;
	char resp[100];
	int ret;

	// Need to wait AT server is ready
	while (!at_command_server_ready())
	{
		sleep(1);
	}

	// set indication callback function
	atclient_set_ind_cb(atclient_get_indication);

	while (1)
	{
		size_t i;

		count++;
		LOG_PRINTF("%s: test count %u", __func__, count);

		for (i = 0; i < sizeof(atcmdlist) / sizeof(atcmdlist[0]); i++)
		{
			memset(resp, 0, sizeof(resp));
			LOG_PRINTF("ATCmd: %s", atcmdlist[i]);
			ret = atclient_send(atcmdlist[i], 30, 1, resp, sizeof(resp));
			if (ret == 0)
			{
				LOG_PRINTF("ATResp: %s", resp);
			}
			sleep(1);
		}

		sleep(15); // 15 seconds
	}
}

int main(void)
{
	int ret;
	OSTaskRef task_ref; // because following task will never exit, so we do not use task handle, so we don't care it's handle

	ret = OSATaskCreate(&task_ref, NULL, TASK_STACK_SIZE, OS_APP_PRIORITY, "app", atclient_task, NULL);
	ASSERT(ret == OS_SUCCESS);
	return 0;
}
